<template>
  <BasicModal
    v-bind="$attrs"
    destoryOnClose
    width="30%"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, computed, toRaw, PropType, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { transferFlowApi, turnToDoFlowApi, transferIdeaFlowApi } from '/@/api/flow/flow';
  import { BTN_EVENT_TYPE } from '/@/views/config-center/model-design/model';
  import { FlowHandleBtn } from '../types/model';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  import { FormSchema } from '/@/components/Table';

  // 流程传阅，意见征询，转批弹框（表格上面和流程里面共用）
  export default defineComponent({
    name: 'ComFlowModel',
    components: { BasicModal, BasicForm },
    props: {
      title: String,
      type: String as PropType<BTN_EVENT_TYPE>,
      formScheama: {
        type: Array as PropType<FormSchema[]>,
        deftault: () => [],
      },
    },
    emits: ['success', 'register', 'cancel'],
    setup(props, { emit }) {
      const title = ref('');
      const selectUserVal = ref<any[]>([]);
      const isUpdate = ref(false);
      const isFlowDetail = ref(false);

      const getTitle = computed(() => {
        if (props.title) props.title;
        return title.value;
      });

      const { createMessage } = useMessage();

      const formScheamaData = computed(() => {
        return props.formScheama;
      });

      const [registerForm, { setProps, getFieldsValue, setFieldsValue, resetFields, validate }] =
        useForm({
          labelWidth: 110,
          baseColProps: { span: 24 },
          showActionButtonGroup: false,
        });

      async function updateSchemaFn(label) {
        console.log('unref(formScheama2)', unref(formScheamaData), label);

        const fieldSchemaArr = cloneDeep(unref(formScheamaData));

        fieldSchemaArr &&
          fieldSchemaArr.forEach((item) => {
            item.label = `${label}${item.label}`;
          });

        console.log('fieldSchemaArr', fieldSchemaArr);

        setProps({ schemas: fieldSchemaArr });
      }

      let handOptions;

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log('comFlow', data, getFieldsValue());
        setModalProps({ confirmLoading: false });
        handOptions = data;
        title.value = data.label;
        isUpdate.value = !!data.isUpdate;
        isFlowDetail.value = !!data.isFlowDetail;

        await updateSchemaFn(data.label);
        resetFields();

        // 流程传阅，意见征询，流程转批
        let workItemName =
          data.isPassArr && data.isPassArr.map((item) => item.WorkItemName).join(',');

        //意见征询办理
        if (data.record) {
          workItemName = data.record.WorkItemName;
        }

        setFieldsValue({
          workItemName,
        });
      });

      async function flowFn(label, params, apiFn) {
        const res = await apiFn(params);
        !res && createMessage.success(`${label}成功`);
        res && createMessage.success(`${res}`);
      }

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          console.log('modelvalues', values, toRaw(selectUserVal.value));
          closeModal();
          const { eventType, label, isPassArr, record, guid } = handOptions;

          let consultParams;
          let handParams;
          let patchParams;

          // 操作征询办理
          if (record) {
            const { WorkItemID, EntryID, UserID } = record;
            const { readComment } = values;

            consultParams = {
              guid,
              workItemId: WorkItemID,
              entryId: EntryID,
              userId: UserID,
              transStatus: 2,
              readComment,
            };
          } else {
            // 流程传阅，意见征询，流程转批
            const workItemTranDtoList =
              isPassArr &&
              isPassArr.map((item) => {
                return { workItemId: item.WorkItemID, entryId: item.EntryID };
              });

            const { workItemName, acceptIdList, transComment, turntoMemo } = values;

            handParams = {
              guid,
              acceptIdList: acceptIdList && acceptIdList.map((item) => item.userId),
              operationType: 0,
              transComment,
              workItemTranDtoList,
            };

            const acceptIdListTemp =
              acceptIdList &&
              acceptIdList.map((item) => {
                return { acceptId: item.userId, acceptName: item.name };
              });

            // 转批参数,转批只能选择一个
            patchParams = {
              guid,
              workItemName,
              flowId: isPassArr && isPassArr[0].FlowID,
              activityId: isPassArr && isPassArr[0].ActivityID,
              activityName: isPassArr && isPassArr[0].ActivityName,
              turntoMemo,
              turntoType: 0,
              ...workItemTranDtoList[0],
              ...acceptIdListTemp[0],
            };
          }

          switch (eventType) {
            case BTN_EVENT_TYPE.FLOWHANDROUND:
            case FlowHandleBtn.Circulation:
              // 传阅
              await flowFn(label, handParams, transferFlowApi);
              break;
            case BTN_EVENT_TYPE.FLOWCONSULT:
            case FlowHandleBtn.Consultation:
              // 意见征询
              if (!isUpdate.value || isFlowDetail.value) {
                handParams.operationType = 1;
                await flowFn(label, handParams, transferFlowApi);
              } else {
                // 表格内办理
                consultParams.operationType = 1;
                await flowFn(label, consultParams, transferIdeaFlowApi);
              }
              break;
            case BTN_EVENT_TYPE.FLOWTURNBATCH:
            case FlowHandleBtn.TurnToDo:
              // 转办
              await flowFn(label, patchParams, turnToDoFlowApi);
              break;
          }
          resetFields();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
